<!--
 * @Author: XY
 * @Date: 2023-11-09 13:27:45
 * @LastEditors: fleeting-ln 3518413017@qq.com
 * @LastEditTime: 2023-12-17 21:03:12
 * @LastEditors: XY
 * @LastEditTime: 2023-11-22 14:55:04
 * @FilePath: \friendsApp\see_you\src\views\homePage\index.vue
 -->
<template>
  <div class="box">
    <div class="head" id="head">
      <div class="head-location" @click="getCode">
        {{ cityText[0] || '获取中...' }}
        <img src="@/assets/iconIndex/location.png" alt="" />
      </div>
      <div class="head-search">
        <router-link to="/search">
          <input type="text" placeholder="请输入姓名" />
        </router-link>
      </div>
      <div class="head-sex-icon1" @click="setSex('boy')">
        <img v-if="isBoy" src="@/assets/iconIndex/boyBtn.png" alt="" />
        <img v-else src="@/assets/iconIndex/male.png" alt="" />
      </div>
      <div class="head-sex-icon2" @click="setSex('girl')">
        <img v-if="isGirl" src="@/assets/iconIndex/girlBtn.png" alt="" />
        <img v-else src="@/assets/iconIndex/female.png" alt="" />
      </div>
    </div>
    <!-- 列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <template #pulling="props">
        <img class="doge" src="https://img01.yzcdn.cn/vant/doge.png"
          :style="{ transform: `scale(${props.distance / 80})` }" />
      </template>

      <!-- 释放提示 -->
      <template #loosing> 最后刷新：{{ nowTime }} </template>

      <!-- 加载提示 -->
      <template #loading> 正在刷新数据中。。。 </template>
      <van-list v-model="loading" :finished="finished" :finished-text="finishText" @load="getInit"
        :style="{ height: windowHeight - stickyHeight - tabbarHeight + 'px' }">
        <div class="list">
          <div class="list-info" v-for="(item, index) in dataList" :key="index" @click="goPage(item)">
            <div class="list-info-headImg">
              <img :src="item.avatar" alt="" />
            </div>
            <div class="list-info-message">
              <div class="list-info-message-line1">
                <div class="list-info-message-line1-name">
                  {{ item.nickname }}
                </div>
                <div class="list-info-message-line1-age" v-if="item.sex == 2">
                  <img src="@/assets/iconIndex/girl.png" />{{ item.age }}
                </div>
                <div class="list-info-message-line1-age" v-if="item.sex == 1" style="background: #cde1fd; color: #3662ec">
                  <img src="@/assets/iconIndex/boy.png" />{{ item.age }}
                </div>
                <div class="list-info-message-line1-vip" v-if="item.is_svip == 1">
                  <img src="@/assets/iconIndex/vip.png" alt="" />
                </div>
                <p class="list-info-message-line1-status">
                  {{ item.last_time }}
                </p>
              </div>
              <div class="list-info-message-line2">
                <div class="list-info-message-line2-describe">
                  {{ item.describe }}
                </div>
                <div class="list-info-message-line2-distance">
                  {{ item.distance }}
                </div>
              </div>
              <div class="list-info-message-line3">
                <img v-for="itemImg in item.albums" :key="itemImg" :src="itemImg" alt=""
                  @click.stop="onPreviewPicture(item.albums)" />
              </div>
              <div class="list-info-message-line4">
                <div class="list-info-message-line4-score">
                  <div>综合评分</div>
                  <van-rate readonly v-model="item.overall_score" allow-half void-icon="star" void-color="#eee"
                    color="#ffd21e" size="12" />
                  <div>{{ item.overall_score }}分</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import { sy_convertCityNameToCityCode } from '@/utils/location_convert'
import { getReigonTree, positioning } from '@/api/index'
import { Toast } from 'vant'
import middleUtils from '@/utils/middleUtil'
import { parseTime } from '@/utils/fun'
import { ImagePreview } from 'vant'
import axios from "axios";

export default {
  name: 'HomeView',
  data() {
    return {
      finishText: '没有更多了',
      nowTime: '',
      cityText: [], //当前城市
      mark: null,
      reLnglat: null,
      sum: 1,
      markerArr: [],
      searchParameter: {
        //  * 城市编码  为空为首页检索接口
        city_code: '',
        // * 城市名称
        city_name: '',
        // * 分页参数    * 页大小 （默认10）
        limit: 10,
        // * 经度 必填
        lng: '',
        // * 纬度 必填
        lat: '',
        // * 用户类型 默认 merchant * merchant 商家 * user 用户 必填
        userType: '',
        // * 昵称
        nickname: '',
        // * 分页参数* 当前页 （默认1）
        page: 1,
        // * 性别  1男 2女 0全部
        sex: 0,
        limit: 10,
      },
      loading: false,
      finished: true,
      refreshing: false,
      value: 3.5,
      isBoy: true,
      isGirl: true,
      dataList: [],
      stickyHeight: 0,
      windowHeight: 0,
      tabbarHeight: 0,
      isdsq: false, //计时器控制
    }
  },
  beforeRouteUpdate(to, from, next) {
    console.log('到', to, '从', from)
    // 判断路由是否不相等，不相等时继续执行
    if (to.fullPath != from.fullPath) {
      next()
    }
  },
  watch: {
    // searchParameter: {
    //   deep: true, //deep深度监听（只有再监听复杂数据类型才需要开启深度监听）
    //   handler(newvalue, odlvalue) {
    //     if (newvalue.lat == '' || newvalue.lng == '') {
    //       this.onRefresh()
    //     }
    //   },
    // },
    // dataList: {
    //   deep: true,
    //   handler(newvalue, odlvalue) {
    //     console.log(newvalue, odlvalue)
    //     if (newvalue.length == 0) {
    //       this.getInit()
    //     }
    //   },
    // },
    // $route(to, from) {
    //   console.log('?')
    //   if (from.path == '/Login' && this.dataList.length == 0) {
    //     console.log('?')

    //     this.onRefresh()
    //   }
    // },
  },
  async mounted() {
    this.stickyHeight = document.getElementById('head').clientHeight
    this.windowHeight = document.documentElement.clientHeight
    this.tabbarHeight = document.getElementById('tabbar').clientHeight
    await this.getAmap();

  },
  beforeDestroy() {
    middleUtils.$off('getCity')
  },

  methods: {
    onRefresh() {
      // 清空列表数据
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.searchParameter.page = 1
      this.dataList = []
      this.getInit()
    },
    getAmap() {
      const that = this;
      AMap.plugin("AMap.Geolocation", () => {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          //是否使用安卓定位sdk用来进行定位，需要安卓端sdk配合
          useNative: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000,
          needAddress: true,
        });

        geolocation.getCurrentPosition((status, result) => {  //获取用户当前的精确位置
          console.log(result, status);
          if (status == "complete") {

            //重点：设置了needAddress属性 定位返回的信息回包含addressComponent对象，里面返回的内容跟regeo请求返回addressComponent 对象一致。
            if (result.addressComponent) {
              //业务逻辑代码
            } else {
              this.searchParameter.lat = result.position.lat
              this.searchParameter.lng = result.position.lng
              that.surePosition(result.position.lng, result.position.lat) //防止返回信息不同
            }
          }
          else {
            geolocation.getCityInfo((status, result) => {   //只能获取当前用户所在城市和城市的经纬度
              if (status == "complete") {
                //业务逻辑代码
              } else {
                that.finishText = '未获取定位'
              }
            })
          }
        })

      })
    },
    surePosition(re0, re1) {
      console.log(re0, re1)
      const that = this;
      let key = '8c2e8be40d8b21a1875d08751d0de95e'
      axios.get(`https://restapi.amap.com/v3/geocode/regeo?key=${key}&location=${re0 + ',' + re1}&extensions=all`)
        .then((response) => {
          if (response.data.status) {
            const result = response.data.regeocode
            that.cityText = sy_convertCityNameToCityCode(
              result.addressComponent.city && result.addressComponent.city.length > 0
                ? result.addressComponent.city
                : result.addressComponent.province,
              result.addressComponent.adcode
            )
            that.searchParameter.city_code = that.cityText[1]
            that.searchParameter.city_name = that.cityText[0]
            let val = {
              lng: re0,
              lat: re1,
              city_code: that.cityText[1],
              city_name: that.cityText[0],
            }
            positioning(val).then((res) => { })
            that.onRefresh()
          } else {
            that.finishText = '未获取定位'
          }
        })
    },

    getInit() {
      if (
        this.searchParameter.lng &&
        this.searchParameter.lat
      ) {
        this.getData()
      } else {
        this.getAmap()
      }
    },
    goPage(user) {
      if (user.is_merchant == 1) {
        this.$router.push({
          path: '/detail',
          query: {
            id: user.uid,
          },
        })
      } else {
        this.$router.push({
          path: '/userDetail',
          query: {
            id: user.uid,
          },
        })
      }
    },
    // 获取数据
    getData() {
      const queryString = Object.keys(this.searchParameter)
        .map((key) => {
          if (this.searchParameter[key] && !!this.searchParameter[key]) {
            return `${key}=${this.searchParameter[key]}`
          }
        })
        .filter((res) => {
          return res
        })
        .join('&')
      getReigonTree(queryString).then((res) => {
        this.nowTime = parseTime(new Date())
        if (res.data.count == 0 || res.data.count > this.dataList.length) {
          res.data.list.forEach((el) => {
            el.describe =
              el?.height +
              'cm |' +
              el?.weight +
              'kg |' +
              el?.constellation +
              (el?.constellation ? '|' : '') +
              el?.occupation

            el.overall_score = parseFloat(el.overall_score)
          })
          this.searchParameter.page++
          this.dataList = this.dataList.concat(...res.data.list)
        }
        if (res.data.count <= this.dataList.length) {
          this.finished = true
        } else {
          this.finished = false
        }
        this.refreshing = false
        this.loading = false
      })
    },
    async setSex(type) {
      if (type == 'boy') {
        this.isBoy = !this.isBoy
      } else {
        this.isGirl = !this.isGirl
      }
      if (this.isBoy) {
        this.searchParameter.sex = 1
      } else {
        this.searchParameter.sex = 2
      }
      if (!this.isBoy && !this.isGirl) {
        this.isGirl = true
        this.isBoy = true
        this.searchParameter.sex = 0
      } else if (this.isBoy && this.isGirl) {
        this.searchParameter.sex = 0
      }
      this.onRefresh()

    },
    //获取定位
    getCode() {
      let self = this
      middleUtils.$on('getCity', (city) => {
        self.cityText = [city.name, city.city_code]
        self.searchParameter.city_code = this.cityText[1]
        self.searchParameter.city_name = this.cityText[0]
        self.onRefresh()
      })
      this.$router.push({ path: '/location' })
    },
    onPreviewPicture(albums) {
      ImagePreview({
        images: [...albums],
      })
    },
  },
}
</script>

<style  lang="scss" scoped>
::v-deep .van-list {
  overflow-y: auto !important;
}

.box {
  // padding: 16px;
  height: 100vh !important;
  overflow-y: hidden !important;
  box-sizing: border-box;
}

.content-class {
  overflow-y: auto;
}

.head {
  padding: 26px 16px 16px 16px;
  // padding-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  font-weight: 400;
  color: #1a1a1a;

  >div:nth-of-type(-n + 3) {
    margin-right: 8px;
  }

  &-search {
    flex: 1;

    input {
      background: #ffffff;
      border-radius: 8px;
      border: 1px solid #cde1fd;
      padding: 5px 10px;
      width: 89%;
    }
  }

  &-sex-icon1 {
    display: flex;
  }

  &-sex-icon2 {
    display: flex;
  }
}

.list {
  // margin-top: 20px;
  padding: 20px 16px 0px 16px;

  &-info {
    display: flex;
    margin-bottom: 20px;

    &-headImg {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      margin-right: 7px;

      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }

    &-message {
      flex: 1;

      >div {
        display: flex;
        align-items: center;
      }

      &-line1 {
        position: relative;

        >div {
          margin-right: 8px;
        }

        &-name {
          font-size: 16px;
          font-weight: 500;
          color: #1a1a1a;
        }

        &-age {
          width: 38px;
          height: 16px;
          background: #fcdbdb;
          border-radius: 8px;
          color: #fa5151;
          font-size: 12px;
          display: flex;
          align-items: center;
          justify-content: center;

          img {
            margin-right: 2px;
          }
        }

        &-vip {
          display: flex;
          align-items: center;
        }

        &-status {
          position: absolute;
          right: 0;
          font-size: 12px;
          font-weight: 400;
          color: #ff8f1f;
        }
      }

      &-line2 {
        display: flex;
        justify-content: space-between;
        font-size: 12px;
        color: #767676;
        line-height: 12px;
        padding: 8px 0;

        &-describe {}

        &-distance {}
      }

      &-line3 {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-column-gap: 15px;

        img {
          width: 80px;
          height: 80px;
          border-radius: 8px;
        }
      }

      &-line4 {
        padding: 8px 0;

        &-score {
          display: flex;
          align-items: center;
          color: #3764ec;
        }
      }
    }
  }
}

::-webkit-scrollbar {
  display: none;
  /* Chrome Safari */
}
</style>
